
from tools9 import (time_to_minutes,calculate_work_end_time,parse_shift,
                    safe_parse_list,get_allowed_shifts,
                    calculate_work_start_time,calculate_unload_done_time,calculate_arrive_time,
                    double_zero_priority_sort,check_ab_vehicles)
import pandas as pd

def jieche_changde_tasks(df,driver_df,vehicle_df,assigned_vehicles,assigned_drivers):
    '''
    1.接车，铝卷
    2. 根据人数，筛选车次，间隔要大于9h
    '''
    result_df = []
    available_drivers = driver_df[ (~driver_df['driver_name'].isin(assigned_drivers)) &
                                   (driver_df['region'] == '常德')]
    # 筛选任务
    available_driver_count = len(available_drivers)
    if available_driver_count >= 4:
        capacity = 4
    elif available_driver_count in [2,3]:
        capacity = 2
    else:
        capacity = 0
    jieche_changde_df = df[(df['cargo_type'] == "铝卷") &
                           (df['is_transfer'] == '是')
                           ].copy()
    m_jieche_changde_df = jieche_changde_df[
        (jieche_changde_df['departure_time'].apply(time_to_minutes) < 14 * 60)
    ]
    a_jieche_changde_df = jieche_changde_df[
        (jieche_changde_df['departure_time'].apply(time_to_minutes) >= 14 * 60)
    ]

    if capacity == 2:
        task1 = m_jieche_changde_df.iloc[0]
        task2 = a_jieche_changde_df.iloc[0]
        df1 = task1._append(task2)
        result0 = jieche_changde_task(task1, task2, driver_df, vehicle_df, assigned_vehicles, assigned_drivers)
        for result in result0:
            assigned_drivers.add(result['司机姓名'])
            assigned_vehicles.add(result['车辆ID'])
        result_df.extend(result0)
        df1 = pd.DataFrame([task1.to_dict(), task2.to_dict()])
    elif capacity == 4:
        task1 = m_jieche_changde_df.iloc[0]
        task2 = a_jieche_changde_df.iloc[0]
        result1 = jieche_changde_task(task1,task2, driver_df, vehicle_df, assigned_vehicles, assigned_drivers)
        for result in result1:
            assigned_drivers.add(result['司机姓名'])
            assigned_vehicles.add(result['车辆ID'])
        result_df.extend(result1)
        task3 = m_jieche_changde_df.iloc[1]
        task4 = a_jieche_changde_df.iloc[1]
        result2 = jieche_changde_task(task3,task4, driver_df, vehicle_df, assigned_vehicles, assigned_drivers)
        for result in result2:
            assigned_drivers.add(result['司机姓名'])
            assigned_vehicles.add(result['车辆ID'])
        result_df.extend(result2)
        df1 = pd.DataFrame([task1.to_dict(), task2.to_dict(),task3.to_dict(), task4.to_dict()])

    return result_df,assigned_vehicles,assigned_drivers,df1

def jieche_changde_task(task1,task2,driver_df,vehicle_df,assigned_vehicles,assigned_drivers):

    departure_time1 = task1['departure_time']
    departure_time2 = task2['departure_time']
    task_shift1 = parse_shift(departure_time1)
    task_shift2 = parse_shift(departure_time2)

    # 先安排司机
    selected_driver1 = assign_driver_for_jieche_changde(
        task1, driver_df,assigned_drivers
    )
    assigned_for_task2 = set(assigned_drivers)
    assigned_for_task2.add(selected_driver1['driver_name'])
    selected_driver2 = assign_driver_for_jieche_changde(
        task2, driver_df, assigned_for_task2
    )

    selected_vehicle = assign_vehicle_for_jieche_changde(
        task1, task_shift1, vehicle_df, assigned_vehicles,selected_driver1
    )

    # 计算到货时间
    arrive_time1 = calculate_arrive_time(cargo_type=task1['cargo_type'],
                                        dep_time=task1['departure_time'],
                                        is_second_special=False
                                        )
    # 计算卸货完成时间
    unload_done_time1 = calculate_unload_done_time(arrive_time=arrive_time1,
                                                  cargo_type=task1['cargo_type'],
                                                  load_time=task1['load_time']
                                                  )

    end_time1 = calculate_work_end_time(cargo_type = task1['cargo_type'],
                                       unload_done_time = unload_done_time1,
                                       region = selected_driver1['region'],
                                       is_transfer = task1['is_transfer'],
                                       load_time = task1['load_time']
                                       )

    # 计算到货时间
    arrive_time2 = calculate_arrive_time(cargo_type=task2['cargo_type'],
                                         dep_time=task2['departure_time'],
                                         is_second_special=False
                                         )
    # 计算卸货完成时间
    unload_done_time2 = calculate_unload_done_time(arrive_time=arrive_time2,
                                                   cargo_type=task2['cargo_type'],
                                                   load_time=task2['load_time']
                                                   )

    end_time2 = calculate_work_end_time(cargo_type=task2['cargo_type'],
                                       unload_done_time=unload_done_time2,
                                       region=selected_driver2['region'],
                                       is_transfer=task2['is_transfer'],
                                       load_time=task2['load_time']
                                       )
    return [{
        '发车时间': departure_time1,
        '装货时间': task1['load_time'],
        '货物类型': '铝卷',
        '车辆ID': selected_vehicle['vehicle_id'],
        '车辆类型': selected_vehicle['type'],
        '车牌号': selected_vehicle['plate_number'],
        '司机ID': selected_driver1['driver_id'],
        '司机姓名': selected_driver1['driver_name'],
        '司机所属地区': selected_driver1['region'],
        '是否接车': task1['is_transfer'],
        '收车时间': end_time1
    },
    {
        '发车时间': departure_time2,
        '装货时间': task2['load_time'],
        '货物类型': '铝卷',
        '车辆ID': selected_vehicle['vehicle_id'],
        '车辆类型': selected_vehicle['type'],
        '车牌号': selected_vehicle['plate_number'],
        '司机ID': selected_driver2['driver_id'],
        '司机姓名': selected_driver2['driver_name'],
        '司机所属地区': selected_driver2['region'],
        '是否接车': task2['is_transfer'],
        '收车时间': end_time2
    }]


def assign_driver_for_jieche_changde(task, driver_df,assigned_drivers):
    '''
    1.常德
    2. 早晚班
    3. 休息时间
    '''
    available_drivers = driver_df[(~driver_df['driver_name'].isin(assigned_drivers)) &
                                  (driver_df['driver_name'].notna()) &
                                  (driver_df['region'] == '常德')].copy()

    available_drivers['start_time'] = available_drivers['region'].apply(
        lambda x: calculate_work_start_time(load_time=task['load_time'],
                                            departure_time=task['departure_time'],
                                            region=x,
                                            cargo_type=task['cargo_type'])
    )
    available_drivers = available_drivers[
        time_to_minutes(available_drivers['start_time']) +24*60 - time_to_minutes(available_drivers['end_time']) > 9*60]

    available_drivers['time_priority'] = time_to_minutes(available_drivers['start_time']) - time_to_minutes(
        available_drivers['end_time'])


    available_drivers['count_priority'] = available_drivers.apply(double_zero_priority_sort, axis=1)


    available_drivers = available_drivers.sort_values(
        by=['time_priority','driver_id'],
        ascending=[False,  True]
    )
    print(available_drivers)
    return available_drivers.iloc[-1]
def assign_vehicle_for_jieche_changde(task, task_shift, vehicle_df, assigned_vehicles, selected_driver):
    '''


    1. 可用车辆：9025/2027
    2. ab角
    '''
    available_vehicles = vehicle_df[(~vehicle_df['vehicle_id'].isin(assigned_vehicles)) & (vehicle_df['plate_number']).isin(['湘AM9025','湘AM2027'])].copy()

    # 计算AB角优先级
    available_vehicles['ab_priority'] = available_vehicles['ab_drivers'].apply(
        lambda x: check_ab_vehicles(x, selected_driver['driver_name'])
    )

    # 按AB角优先级排序（A角优先），然后按司机ID排序
    available_vehicles = available_vehicles.sort_values(
        by=['ab_priority', 'vehicle_id'],
        ascending=[False, True]
    )
    selected_vehicle = available_vehicles.iloc[0]

    if selected_vehicle is None:
        print(f"没有可用车辆用于常德铝卷接车任务: {task['departure_time']}")
        return None

    return selected_vehicle
